//
//  LZStartGroupViewController.m
//  LYLazizDevelopDemo
//
//  Created by xbn_iMac on 2016/11/8.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZStartGroupViewController.h"
#import "UIViewController+NavigationItemSetting.h"
#import "LZFightGroupDetailOrderRulesCell.h"
#import "LZFightGroupDetailRulesOfUseCell.h"
#import "LZFightGroupDetailMealsTimeCell.h"
#import "LZVideoPublisherCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "LZGrabCouponAndFightGroupsDetialModel.h"
#import "LZGrouponPresenter.h"
#import "TShareEventHandler.h"
#import "TShareView.h"
#import "LZAlertView.h"
#import "Masonry.h"
#import "LZDateFormatterManager.h"

static NSString * kOrderRulesCell = @"orderRulesCell";
static NSString * kRulesOfUseCell = @"rulesOfUseCell";
static NSString * kMealsTimeCell  = @"mealsTimeCell";
static NSString * kPubliserCell   = @"publisherCell";

@interface LZStartGroupInputCell :UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *labTitle;
@property (weak, nonatomic) IBOutlet UITextField *textContent;

@end

@implementation LZStartGroupInputCell


@end


@interface LZStartGroupViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet LZStartGroupInputCell *inputCell;
@property (strong, nonatomic) UIButton *rightButton;

@property (strong, nonatomic) UIView *rulesHeaderView;

@property (nonatomic, strong) TShareView * shareView;

@property (strong, nonatomic) NSString *shareImageUrl;

@end

@implementation LZStartGroupViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.umLogPageViewName = @"开团页面";
    
    self.title = LZLocalizedString(@"group_start_group", nil);
    self.inputCell.textContent.placeholder = LZLocalizedString(@"group_enter_group_name", nil);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged) name:UITextFieldTextDidChangeNotification object:self.inputCell.textContent];

    [self registerCell];
    [self configNavigationBarRightButton];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)textFieldChanged {
    if (self.inputCell.textContent.text.length>50) {
        self.inputCell.textContent.text = [self.inputCell.textContent.text substringToIndex:50];
    }
    if (self.inputCell.textContent.text.length>0) {
        [self.rightButton setTitleColor:UIColorFromRGB(0xff7a21, 1) forState:UIControlStateNormal];
    }
    else {
        [self.rightButton setTitleColor:UIColorFromRGB(0x666666, 1) forState:UIControlStateNormal];
    }
    self.rightButton.userInteractionEnabled = self.inputCell.textContent.text.length>0;
    NSLog(@"%@",self.inputCell.textContent.text);
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark private action
- (void)configNavigationBarRightButton {
    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.rightButton setTitle:LZLocalizedString(@"review_submit", nil) forState:UIControlStateNormal];
    self.rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.rightButton setTitleColor:UIColorFromRGB(0x666666, 1) forState:UIControlStateNormal];
    [self.rightButton sizeToFit];
    self.rightButton.frame = CGRectMake(0, 0, CGRectGetWidth(self.rightButton.bounds), 40);
    self.rightButton.userInteractionEnabled = NO;
    [self.rightButton addTarget:self action:@selector(navigationBarRightButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self navigationItemSetting:@[self.rightButton] type:NAVIGATIONITEMSETTING_RIGHT];
}

- (void)navigationBarRightButtonClickAction:(UIButton*)sender {
    
    NSString *submitString = [self.inputCell.textContent.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (submitString.length == 0) {
        // 名称不能为空
        LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"group_name_required", nil) andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
        [alert show];
    }
    
    WS(weakSelf)
    self.rightButton.userInteractionEnabled = NO;
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:NO];
    [LZGrouponPresenter startGroupWithGroupName:self.inputCell.textContent.text andSellerId:self.rulesModel.sellerId andPromotionId:self.rulesModel.videoId ResultSuccess:^(NSString *groupPicture){
        [weakSelf stopLoadingViewForView:weakSelf.view];
        weakSelf.shareImageUrl = groupPicture;
        [weakSelf showInviteAlert];
        weakSelf.rightButton.userInteractionEnabled = YES;
    } ResultFailed:^(NSString *remind) {
        [weakSelf stopLoadingViewForView:weakSelf.view];
        weakSelf.rightButton.userInteractionEnabled = YES;
        if ([remind isEqualToString:@"0500021"]) {
            // 名称已存在
            LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"group_name_exits", nil) andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
            [alert show];
        }
        DLog(@"失败了");
    }];
}

#pragma mark -
#pragma mark register cell
- (void)registerCell
{
    [self.tableView registerNib:[UINib nibWithNibName:@"LZFightGroupDetailOrderRulesCell" bundle:nil] forCellReuseIdentifier:kOrderRulesCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LZFightGroupDetailRulesOfUseCell" bundle:nil] forCellReuseIdentifier:kRulesOfUseCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LZFightGroupDetailMealsTimeCell" bundle:nil] forCellReuseIdentifier:kMealsTimeCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LZVideoPublisherCell" bundle:nil] forCellReuseIdentifier:kPubliserCell];
    
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return self.inputCell;
    }else{
        switch (indexPath.row) {
            case 0:{
                LZFightGroupDetailOrderRulesCell *cell = [tableView dequeueReusableCellWithIdentifier:kOrderRulesCell];
                [cell loadMembersNum:self.rulesModel.grouponCount FinishedTime:[[LZDateFormatterManager shareInstance] stringFromDoubleTimestampHavePointyyyyMMdd:self.rulesModel.grouponEndTime]];
                return cell;
            }
                
                break;
            case 1:{
                LZFightGroupDetailRulesOfUseCell *cell = [tableView dequeueReusableCellWithIdentifier:kRulesOfUseCell];
                [cell loatGrouponName:self.rulesModel.grouponName RulesContent:self.rulesModel.grouponRemindRule ExpirationTime:[[LZDateFormatterManager shareInstance] stringFromDoubleTimestampHavePointyyyyMMdd:self.rulesModel.grouponDeadline]];
                return cell;
            }
                
                break;
            case 2:{
                LZFightGroupDetailMealsTimeCell *cell = [tableView dequeueReusableCellWithIdentifier:kMealsTimeCell];
                NSString *everyDayValid = [self.rulesModel getGroupEverydayValid];
                [cell loadValidExcept:self.rulesModel.grouponExceptTime EverydayValid:everyDayValid otherContent:self.rulesModel.grouponRemindAppoint];
                return cell;
            }
                
                break;
            case 3:{
                LZVideoPublisherCell *cell = [tableView dequeueReusableCellWithIdentifier:kPubliserCell];
                [cell loadPublisherName:self.rulesModel.restaurantName];

                return cell;
            }
                
                break;
                
            default:
                break;
        }
    }
    return nil;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 53;
    }else{
        WS(weakSelf)
        switch (indexPath.row) {
            case 0:
                return [tableView fd_heightForCellWithIdentifier:kOrderRulesCell configuration:^(id cell) {
                    LZFightGroupDetailOrderRulesCell *cellTemp = (LZFightGroupDetailOrderRulesCell *)cell;
                    [cellTemp loadMembersNum:weakSelf.rulesModel.grouponCount FinishedTime:[[LZDateFormatterManager shareInstance] stringFromDoubleTimestampHavePointyyyyMMdd:weakSelf.rulesModel.grouponEndTime                                                                                                                                                                                       ]];
                    
                }];
                break;
            case 1:
                return [tableView fd_heightForCellWithIdentifier:kRulesOfUseCell configuration:^(id cell) {
                    LZFightGroupDetailRulesOfUseCell *cellTemp = (LZFightGroupDetailRulesOfUseCell *)cell;
                    [cellTemp loatGrouponName:weakSelf.rulesModel.grouponName RulesContent:weakSelf.rulesModel.grouponRemindRule ExpirationTime:[[LZDateFormatterManager shareInstance] stringFromDoubleTimestampHavePointyyyyMMdd:self.rulesModel.grouponDeadline]];
                }];
                break;
            case 2:
                return [tableView fd_heightForCellWithIdentifier:kMealsTimeCell configuration:^(id cell) {
                    LZFightGroupDetailMealsTimeCell *cellTemp = (LZFightGroupDetailMealsTimeCell *)cell;
                    NSString *everyDayValid = [weakSelf.rulesModel getGroupEverydayValid];
                    [cellTemp loadValidExcept:weakSelf.rulesModel.grouponExceptTime EverydayValid:everyDayValid otherContent:weakSelf.rulesModel.grouponRemindAppoint];
                }];
                break;
            case 3:
                return [tableView fd_heightForCellWithIdentifier:kPubliserCell configuration:^(id cell) {
                    LZVideoPublisherCell *cellTemp = (LZVideoPublisherCell *)cell;
                    [cellTemp loadPublisherName:weakSelf.rulesModel.restaurantName];
                }];
                break;
                
            default:
                break;
        }
    }
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return 30;
    }
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return self.rulesHeaderView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return 10;
    }
    return 0.01;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (UIView*)rulesHeaderView {
    if (_rulesHeaderView) {
        return _rulesHeaderView;
    }
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 30)];
    v.backgroundColor = [UIColor whiteColor];
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = UIColorFromRGB(0xdddddd, 1);
    [v addSubview:line];
    
    UILabel *l = [[UILabel alloc] init];
    l.backgroundColor = [UIColor whiteColor];
    l.text = LZLocalizedString(@"group_rules", nil);
    l.textAlignment = NSTextAlignmentCenter;
    l.textColor = UIColorFromRGB(0x999999, 1);
    l.font = [UIFont systemFontOfSize:15];
    [v addSubview:l];
    
    [l mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(60, 16));
        make.centerX.equalTo(v);
        make.bottom.mas_equalTo(3);
    }];
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(10);
        make.trailing.mas_equalTo(-10);
        make.height.mas_equalTo(0.5);
        make.centerY.equalTo(l);
    }];
    
    _rulesHeaderView = v;
    return _rulesHeaderView;
}

- (void)showInviteAlert {
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"group_start_success_remind", nil) andImage:nil cancelButtonTitle:LZLocalizedString(@"group_later", nil) otherButtonTitles:LZLocalizedString(@"group_invite", nil),nil];
    [alert show];
    
    WS(weakSelf)
    alert.clickButtonIndexBlock = ^(NSInteger index) {
        if (index == 0) {
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
        }
        else {
            [weakSelf openShare];
        }
    };
}

#pragma mark - Share

- (TShareView *)shareView {
    
    if (_shareView == nil) {
        _shareView = [[TShareView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    }
    
    return _shareView;
}

- (void)openShare {
    WS(weakSelf)
    [self.shareView shareViewOpen];
    self.shareView.shareViewButtonActionBlock = ^(TSHAREVIEW_BUTTON_TYPE type){
        [weakSelf shareAction:type];
    };
    self.shareView.dismissViewBlock = ^() {
        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
    };
}

- (void)shareAction:(NSInteger)type {
    /* 开团邀请 */
    SSDKPlatformType sharePlatformType = SSDKPlatformTypeUnknown;
    
    switch (type) {
        case 0:
            sharePlatformType = SSDKPlatformTypeSMS;
            break;
        case 1:
            sharePlatformType = SSDKPlatformTypeMail;
            break;
        case 2:
            sharePlatformType = SSDKPlatformTypeFacebook;
            break;
        case 3:
            sharePlatformType = SSDKPlatformTypeTwitter;
            break;
    }
    
    WS(weakSelf)
    [TShareEventHandler shareWithShareURL:nil
                            shareImageUrl:@[[NSString stringWithFormat:@"%@%@",APIBaseImageUrl,self.shareImageUrl]]
                               shareTitle:LZLocalizedString(@"share_start_group_invite_title", nil)
                                shareText:[NSString stringWithFormat:LZLocalizedString(@"share_start_group_invite_content", nil),self.inputCell.textContent.text]
                                shareType:sharePlatformType
                                  topView:nil
                               stateBlock:^(SSDKResponseState state) {
                                   DLog(@"%ld",state);
                                   if (weakSelf) {
                                       [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                                   }
                               }];
    
    [self.shareView shareViewClose];
}


@end
